package kr.ac.ml.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
import kr.ac.ml.mvc.FriendList;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

//import org.json.simple.JSONValue;

public class MakeFriendTable extends Action {
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	// throws IOException, ServletException {
	{
		// TODO Auto-generated method stub
		System.out.println("MakeFriendTable");
		// json���� ģ����� �ޱ� ����

		String result;
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		String line;

		InputStream inputstream;
		try {
			inputstream = request.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					inputstream));
			char[] charBuffer = new char[128];
			int bytesRead = -1;
			while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
				stringBuilder.append(charBuffer, 0, bytesRead);
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();

			// System.out.println(request.getParameter("order"));

			// } catch (IOException e) {
			// e.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		result = stringBuilder.toString();
		System.out.println(result);
		response.setContentType("text/html; charset=utf-8");
		String jsonStr = "{code:1011}";
		request.setAttribute("json", jsonStr);
		JsonParser(result);

	}

	private void JsonParser(String result) {
		// TODO Auto-generated method stub
		ListDao dao = new ListDao();
		JSONObject obj;
		try {
			obj = new JSONObject(result);
			JSONArray array = obj.getJSONArray("data");
			System.out.println(array.length());
			int length = array.length();
			ArrayList<FriendList> list = new ArrayList<FriendList>();
			for (int i = 0; i < length; i++) {
				JSONObject json = array.getJSONObject(i);
				System.out.println(json);
				FriendList data = new FriendList(json.getString("empID"),json.getString("fmpID"));		
				list.add(data);			
				System.out.println("list size: " + list.size());				
			}
			dao.insertFriend(list);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
